export default function aiRequest(messages, onProgress, onComplete, onError) {
	const API_URL = 'https://ai.gitee.com/v1/chat/completions'
	const API_KEY = 'ETIEGJL2PBSL4CU6UFV3BBKNBBFHTVXTBOSQ1JND' // 你的 API Key
	let data = {
		model: "DeepSeek-R1",
		stream: true,
		messages: messages.slice(-10),
		// max_tokens: 1024
	}
	
	let thinkMessage = "" // 存储思考的流数据
	let answerMessage = "" // 存储答案的消息
	
	const xhr = new XMLHttpRequest()
	xhr.open('POST', API_URL)
	xhr.setRequestHeader('Content-Type', 'application/json')
	xhr.setRequestHeader('Authorization', `Bearer ${API_KEY}`)
	xhr.timeout = 300000
	xhr.onload = () => {
		if (xhr.status === 200) {
			onComplete?.(thinkMessage, answerMessage)
		} else {
			onError?.(new Error(`请求失败: ${xhr.status}`));
		}
	}
	
	xhr.onprogress = (event) => {
	    if (xhr.readyState === 3) { // 流式数据接收中
			let text = xhr.responseText
			dealData(text)
	    }
	}
	
	xhr.onerror = (error) => onError?.(error)
	xhr.ontimeout = () => {
		onError?.(new Error('请求超时'))
	}
	xhr.send(JSON.stringify(data))
	
	
	async function dealData(text) {
		const lines = text.split("\n")
		answerMessage = ""
		thinkMessage = ""
		
		for (const line of lines) {
			if (line.trim().startsWith("data: ")) {
				const jsonStr = line.replace("data: ", "").trim() // 去掉 "data: "
				if (jsonStr === "[DONE]") {
					onComplete?.(thinkMessage, answerMessage)
					return
				}
				try {
					const jsonData = JSON.parse(jsonStr)
					const thinkContent = jsonData.choices?.[0]?.delta?.reasoning_content || "" // DeepSeek SSE 增量更新
					const answerContent = jsonData.choices?.[0]?.delta?.content || "" // DeepSeek SSE 增量更新
					thinkMessage += thinkContent
					answerMessage += answerContent
				} catch(e) {
					console.error("JSON 解析失败", e)
				}
			}
		}
		onProgress?.(thinkMessage, answerMessage)
	}
	
	return {
		stop: () => {
			xhr.abort()
		}
	}
}